package com.example.jimuyutabletcontrol.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Circle;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.model.LatLng;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.adapter.controlheartbeat.ControlHeartbeatAdapter;
import com.example.jimuyutabletcontrol.bean.HeartbeatInfo;
import com.example.jimuyutabletcontrol.bean.MyOverlay;
import com.example.jimuyutabletcontrol.bean.MyReturnPoint;
import com.example.jimuyutabletcontrol.bean.UnperformedTask;
import com.example.jimuyutabletcontrol.dialog.AUVSettingSelectDialogFragment;
import com.example.jimuyutabletcontrol.dialog.FlickerSettingDialogFragment;
import com.example.jimuyutabletcontrol.dialog.HomeSettingDialogFragment;
import com.example.jimuyutabletcontrol.dialog.NavigationDialogFragment;
import com.example.jimuyutabletcontrol.dialog.SelectAuvDialogFragment;
import com.example.jimuyutabletcontrol.dialog.SetSpeedDialogFragment;
import com.example.jimuyutabletcontrol.dialog.ShowReturnPointDialogFragment;
import com.example.jimuyutabletcontrol.dialog.TaskDialogFragment;
import com.example.jimuyutabletcontrol.dialog.TaskDoConfirmFragment;
import com.example.jimuyutabletcontrol.location.ILocationProvider;
import com.example.jimuyutabletcontrol.location.LocationProvider;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageHandle;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageType;
import com.example.jimuyutabletcontrol.network.udp.UdpSocket;
import com.example.jimuyutabletcontrol.utils.CoordinateTransformUtil;
import com.example.jimuyutabletcontrol.utils.DensityUtil;
import com.example.jimuyutabletcontrol.utils.MeasuringDistancePointHelp;
import com.example.jimuyutabletcontrol.views.gamejoystick.GameJoystickView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.marcoscg.headerdialog.HeaderDialog;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

public class ControlActivity extends AppCompatActivity implements View.OnClickListener,
        AUVSettingSelectDialogFragment.AUVSettingSelectDialogListener, HomeSettingDialogFragment.HomeSettingDialogListener {

    private final int anchorPriority = 3;

    private final int auvPriority = 4;

    private GameJoystickView mJoystickView;

    private IndicatorSeekBar seekBar;

    private MapView mapView;

    private BaiduMap baiduMap;

    private int rotation;

    private Button reset;

    private Button clear;

    private Button btnCourseReversal;

    private UdpMessageHandle handle;

    private Timer timer;

    private TimerTask task;

    private FloatingActionButton fabSend;

    private List<MyOverlay> myOverlays;

    private View mIconView;

    private RecyclerView mHeartbeatRecyclerView;

    private ControlHeartbeatAdapter heartbeatAdapter;

    private UdpMessageHandle heartbeatHandle;

    private List<HeartbeatInfo> heartbeatInfos;

    private MyReturnPoint myReturnPoint;

    private UdpMessageHandle dianLianghandle;

    private MeasuringDistancePointHelp distancePointHelp;

    private TextView measureDistance;

    private TextView unDoTask;

    private List<Overlay> circles;

    private CircleOptions circleOptions = new CircleOptions()
            .fillColor(0xffff0000).radius(2).zIndex(1);

    private int[] colors = new int[]{Color.RED, Color.YELLOW, Color.GREEN, Color.BLACK, Color.GRAY};

    private LatLng latLng;
    private boolean isFirstLoc = true; // 是否首次定位
    public static LocationClient mLocationClient;
    public BDLocationListener myLocationListener = new MyLocationListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.controlinterface_activity);
//        LocationProvider.getInstance().startLocation();
        SDKInitializer.initialize(getApplicationContext());
        initView();
        initRecy();
        setListeners();
        initData();
        initMap();
        setAdapter();
    }

    private void initRecy() {
        mHeartbeatRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index + 1 < heartbeatInfos.size()) {
                    outRect.bottom = DensityUtil.dp2px(ControlActivity.this, 1);
                } else {
                    outRect.bottom = 0;
                }
            }
        });
    }

    /**
     * 设置心跳adapter
     */
    private void setAdapter() {
        heartbeatAdapter = new ControlHeartbeatAdapter(heartbeatInfos);
        mHeartbeatRecyclerView.setAdapter(heartbeatAdapter);
    }

    //配置定位SDK参数
    public static void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        option.setOpenGps(true); // 打开gps

        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    /**
     * 初始化百度地图
     */
    private void initMap() {
//        mapView.showZoomControls(false);
//        MapStatus.Builder builder = new MapStatus.Builder();
//        builder.zoom(4.0f);
//        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//        timer = new Timer();
//        task = new TimerTask() {
//            @Override
//            public void run() {
//                setLocationRegister();
//            }
//        };
//        timer.schedule(task, 2500);

        //获取地图控件引用
        baiduMap = mapView.getMap();
        //普通地图
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        baiduMap.setMyLocationEnabled(true);

        //默认显示普通地图
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //开启交通图
        //mBaiduMap.setTrafficEnabled(true);
        //开启热力图
        //mBaiduMap.setBaiduHeatMapEnabled(true);
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        //配置定位SDK参数
        initLocation();
        mLocationClient.registerLocationListener(myLocationListener);    //注册监听函数
        //开启定位
        mLocationClient.start();
        //图片点击事件，回到定位点
        mLocationClient.requestLocation();
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        heartbeatHandle = new UdpMessageHandle(UdpMessageType.HEARTBEAT, this::refreshHeartbeat);
        handle = new UdpMessageHandle(UdpMessageType.LOCATION, this::refreshLocation);
        dianLianghandle = new UdpMessageHandle(UdpMessageType.DIAN_LIANG, this::dianLiangCallback);
        UdpSocket.getInstance().setMessageCallback(handle);
        UdpSocket.getInstance().setMessageCallback(heartbeatHandle);
        UdpSocket.getInstance().setMessageCallback(dianLianghandle);
        reset.setOnClickListener(v -> {
            String order = "0,0,0,0,0";
            sendOrderByCondition(order);
        });
        clear.setOnClickListener(v -> clearMyOverlays());
        btnCourseReversal.setOnClickListener(v -> returnNavitation());
        mJoystickView.setOnJoystickMoveListener((angle, power, direction) -> {
            switch (direction) {
                case GameJoystickView.UP_DIRECTION: {
                    String order = "0,0,15,-20," + rotation;//前进命令
                    sendOrderByCondition(order);
                }
                break;
                case GameJoystickView.LEFT_DIRECTION: {
                    String order = "-10,10,0,0," + rotation;
                    sendOrderByCondition(order);
                }
                break;
                case GameJoystickView.DOWN_DIRECTION: {
                    String order = "0,0,-20,20," + "-" + "600";//给负转速
                    sendOrderByCondition(order);
                }
                break;
                case GameJoystickView.RIGHT_DIRECTION: {
                    String order = "20,-20,0,-10," + rotation;
                    sendOrderByCondition(order);
                }
                break;
            }
        }, GameJoystickView.DEFAULT_LOOP_INTERVAL);
        seekBar.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                rotation = (int) seekParams.progressFloat;
            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
            }
        });
        (baiduMap = mapView.getMap()).setOnMarkerClickListener(this::setMarker);
        baiduMap.setOnMapLongClickListener(this::setReturnPoint);
        distancePointHelp = new MeasuringDistancePointHelp(this, baiduMap, 2);
        distancePointHelp.setOnMeasuringDistanceListener((isALLShow, distance) -> {
            measureDistance.setVisibility(isALLShow ? View.VISIBLE : View.GONE);
            if (isALLShow) {
                measureDistance.setText("测距距离:" + distance + "米");
            }
        });
        findViewById(R.id.fileSetting).setOnClickListener(v -> {
            SelectAuvDialogFragment auvDialogFragment = SelectAuvDialogFragment.getInstance(myOverlays);
            auvDialogFragment.setOnSelectAuvDialogListener(info ->
                    TaskDialogFragment.getInstance(info.imei).show(getSupportFragmentManager(), "TaskDialogFragment"));
            auvDialogFragment.show(getSupportFragmentManager(), "SelectAuvDialogFragment");
        });
        fabSend.setOnClickListener(this);
        unDoTask.setOnClickListener(v -> {
            if (unDoTask.getText().toString().equals("结束任务")){
                sendOrderByCondition("stop");
            } else {
                TaskDoConfirmFragment doConfirmFragment = TaskDoConfirmFragment.getInstance();
                doConfirmFragment.setOnTaskDoConfirmListener(()->{
                    unDoTask.setText("结束任务");
                });
                doConfirmFragment.show(getSupportFragmentManager(),"TaskDoConfirmFragment");
            }
        });
    }

    private void returnNavitation() {
        SetSpeedDialogFragment dialogFragment = new SetSpeedDialogFragment();
        dialogFragment.setOnSetSpeedDialogListener(speed -> {
            if (null != myReturnPoint) {
                LatLng latLng = ((Marker) myReturnPoint.targetOverlay).getPosition();
                double[] gpsLatlng = CoordinateTransformUtil.bd09towgs84(latLng.longitude, latLng.latitude);
                sendOrderByCondition("gps," + "point:" + new Gson().toJson(gpsLatlng) + "speed:" + speed);
            } else {
                ILocationProvider provider = LocationProvider.getInstance();
                double[] value = provider.getValue();
                double[] value1 = new double[2];
                value1[0] = value[0];
                value1[1] = value[1];
                sendOrderByCondition("gps," + "point:" + new Gson().toJson(value1) + "speed:" + speed);
            }
        });
        dialogFragment.show(getSupportFragmentManager(), "SetSpeedDialogFragment");
    }

    /**
     * auv与下位机电量回调
     *
     * @param s
     */
    private void dianLiangCallback(String s) {
        runOnUiThread(() -> {
            String[] strs = s.split(",AuvAndPhoneElectricQuantity-_-auv-_-");
            if (strs.length != 2) return;
            String[] values = strs[1].split("phone-_-");
            String imei = strs[0];
            String auvDian = values[0];
            String phoneDian = values[1];
            HeartbeatInfo info = getHeartbeatInfoByImei(imei);
            if (null == info) {
                info = new HeartbeatInfo();
                info.imei = imei;
                heartbeatInfos.add(info);
            }
            info.auvElectricQuantity = auvDian;
            info.lowerComputerElectricQuantity = phoneDian;
            info.isShwoElectricQuantity = true;
            heartbeatAdapter.notifyItemChanged(heartbeatInfos.indexOf(info), 1);
            if (heartbeatInfos.size() > 0 && mHeartbeatRecyclerView.getVisibility() == View.GONE) {
                mHeartbeatRecyclerView.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 设置返航点
     *
     * @param latLng
     */
    private void setReturnPoint(LatLng latLng) {
        if (null == myReturnPoint) {
            myReturnPoint = new MyReturnPoint();
            myReturnPoint.bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.return_point);
            myReturnPoint.markerOptions = new MarkerOptions()
                    .position(latLng)
                    .icon(myReturnPoint.bitmapDescriptor)
                    .zIndex(anchorPriority)
                    .animateType(MarkerOptions.MarkerAnimateType.grow);
            myReturnPoint.targetOverlay = baiduMap.addOverlay(myReturnPoint.markerOptions);
        } else {
            if (null != myReturnPoint.targetOverlay && !myReturnPoint.targetOverlay.isRemoved()) {
                ((Marker) myReturnPoint.targetOverlay).setPosition(latLng);
            } else {
                if (null == myReturnPoint.markerOptions) {
                    myReturnPoint.markerOptions = new MarkerOptions();
                }
                if (null == myReturnPoint.bitmapDescriptor || myReturnPoint.bitmapDescriptor.getBitmap() == null
                        || myReturnPoint.bitmapDescriptor.getBitmap().isRecycled()) {
                    myReturnPoint.bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.return_point);
                    myReturnPoint.markerOptions
                            .icon(myReturnPoint.bitmapDescriptor);
                }
                myReturnPoint.markerOptions.position(latLng);
                myReturnPoint.targetOverlay = baiduMap.addOverlay(myReturnPoint.markerOptions);
            }
        }
    }

    /**
     * 刷新心跳
     *
     * @param message
     */
    private void refreshHeartbeat(String message) {
        runOnUiThread(() -> {
            if (TextUtils.isEmpty(message)) return;
            String[] info = message.split("-");
            if (info.length > 1) {
                String imei = info[0].substring(2);
                if (TextUtils.isEmpty(imei)) return;
                int number = Integer.valueOf(info[1]);
                HeartbeatInfo heartbeatInfo = getHeartbeatInfoByImei(imei);
                int index;
                if (null == heartbeatInfo) {
                    heartbeatInfo = new HeartbeatInfo();
                    heartbeatInfo.number = number;
                    heartbeatInfo.imei = imei;
                    index = heartbeatInfos.size();
                    heartbeatInfos.add(heartbeatInfo);
                    heartbeatAdapter.notifyItemInserted(index);
                } else {
                    heartbeatInfo.number = number;
                    index = heartbeatInfos.indexOf(heartbeatInfo);
                    heartbeatAdapter.notifyItemChanged(index, 0);
                }
            }
            if (heartbeatInfos.size() > 0 && mHeartbeatRecyclerView.getVisibility() == View.GONE) {
                mHeartbeatRecyclerView.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 通过imei获取心跳对象
     *
     * @param imei
     * @return
     */
    private HeartbeatInfo getHeartbeatInfoByImei(String imei) {
        if (null == heartbeatInfos || heartbeatInfos.size() == 0 || TextUtils.isEmpty(imei))
            return null;
        for (HeartbeatInfo heartbeatInfo : heartbeatInfos) {
            if (!TextUtils.isEmpty(heartbeatInfo.imei) && heartbeatInfo.imei.equals(imei)) {
                return heartbeatInfo;
            }
        }
        return null;
    }

    /**
     * 发送指令给选中的auv
     *
     * @param order
     */
    private void sendOrderByCondition(String order) {
        for (MyOverlay myOverlay : myOverlays) {
            if (myOverlay.isSelect && !TextUtils.isEmpty(myOverlay.imei)) {
                UdpSocket.getInstance().sendMessage("B" + myOverlay.imei + order);
            }
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        myOverlays = new ArrayList<>();
        heartbeatInfos = new ArrayList<>();
        rotation = 500;
    }

    /**
     * 初始化view
     */
    private void initView() {
        unDoTask = findViewById(R.id.unDoTask);
        mJoystickView = findViewById(R.id.joystick_view);
        seekBar = findViewById(R.id.seekbar);
        reset = findViewById(R.id.reset);
        clear = findViewById(R.id.clear);
        btnCourseReversal = findViewById(R.id.btnCourseReversal);
        mapView = findViewById(R.id.bmapView);
        mHeartbeatRecyclerView = findViewById(R.id.mHeartbeatRecyclerView);
        fabSend = findViewById(R.id.fab);
        measureDistance = findViewById(R.id.measureDistance);
    }

    /**
     * 注册百度地图
     */
    private void setLocationRegister() {
        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        baiduMap.setMyLocationEnabled(true);
        mLocationClient.start();
        mLocationClient.requestLocation();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fab:
                HomeSettingDialogFragment dialogFragment = new HomeSettingDialogFragment();
                dialogFragment.setOnHomeSettingDialogListener(this);
                dialogFragment.show(getSupportFragmentManager(), "HomeSettingDialogFragment");
                break;
        }
    }

    /**
     * auv直航
     *
     * @param imeis
     */
    @Override
    public void onAUVRouteNavigationListener(List<String> imeis) {
        showSettingZhiHangDialog();
    }

    /**
     * auv导航
     *
     * @param imeis
     */
    @Override
    public void onAUVNavigationListener(List<String> imeis) {
        NavigationDialogFragment.getInstance(imeis).show(getSupportFragmentManager(), "NavigationDialogFragment");
    }

    /**
     * 点击信息查询回调
     */
    @Override
    public void onClickSearchInformationListener() {
        SelectAuvDialogFragment auvDialogFragment = SelectAuvDialogFragment.getInstance(myOverlays);
        auvDialogFragment.setOnSelectAuvDialogListener(info -> {
            Intent aUVInformationIntent = new Intent();
            aUVInformationIntent.setClass(ControlActivity.this, AUVInformationActivity.class);
            aUVInformationIntent.putExtra("IMEI", info.imei);
            startActivity(aUVInformationIntent);
        });
        auvDialogFragment.show(getSupportFragmentManager(), "auvDialogFragment");
    }

    /**
     * 点击任务设置回调
     */
    @Override
    public void onClickTaskSettingListener() {
        List<MyOverlay> ors = getSelectedOverlay();
        if (null == ors) {
            Toast.makeText(this, "未有auv连接进来", Toast.LENGTH_SHORT).show();
            return;
        }
        if (ors.size() == 0) {
            Toast.makeText(this, "请选择操控的auv", Toast.LENGTH_SHORT).show();
            return;
        }
        AUVSettingSelectDialogFragment dialogFragment = AUVSettingSelectDialogFragment.getInstance(ors);
        if (null != dialogFragment) {
            dialogFragment.setOnAUVSettingSelectDialogListener(this);
            dialogFragment.show(getSupportFragmentManager(), "AUVSettingSelectDialogFragment");
        }
    }

    /**
     * 点击其他任务设置回调
     */
    @Override
    public void onClickOtherTaskSettingListener() {
        SelectAuvDialogFragment auvDialogFragment = SelectAuvDialogFragment.getInstance(myOverlays);
        auvDialogFragment.setOnSelectAuvDialogListener(info -> FlickerSettingDialogFragment.getInstance(info.imei)
                .show(getSupportFragmentManager(), "FlickerSettingDialogFragment"));
        auvDialogFragment.show(getSupportFragmentManager(), "SelectAuvDialogFragment");
    }

    //实现BDLocationListener接口,BDLocationListener为结果监听接口，异步获取定位结果
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            baiduMap.setMyLocationData(locData);
            // 当不需要定位图层时关闭定位图层
            //mBaiduMap.setMyLocationEnabled(false);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // GPS定位结果
                    Toast.makeText(ControlActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    // 网络定位结果
                    Toast.makeText(ControlActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // 离线定位结果
                    Toast.makeText(ControlActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    Toast.makeText(ControlActivity.this, "服务器错误，请检查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    Toast.makeText(ControlActivity.this, "网络错误，请检查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    Toast.makeText(ControlActivity.this, "手机模式错误，请检查是否飞行", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != distancePointHelp) {
            distancePointHelp.onDestroy();
            distancePointHelp = null;
        }
        if (null != mLocationClient) {
            mLocationClient.unRegisterLocationListener(myLocationListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        myLocationListener = null;
        if (null != handle) {
            UdpSocket.getInstance().removeMessageCallback(handle);
            handle = null;
        }
        if (null != heartbeatHandle) {
            UdpSocket.getInstance().removeMessageCallback(heartbeatHandle);
            heartbeatHandle = null;
        }
        if (null != dianLianghandle) {
            UdpSocket.getInstance().removeMessageCallback(dianLianghandle);
            dianLianghandle = null;
        }
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
        if (null != task) {
            task.cancel();
            task = null;
        }
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.bitmapDescriptor) {
                myOverlay.bitmapDescriptor.recycle();
                myOverlay.bitmapDescriptor = null;
            }
            myOverlay.markerOptions = null;
            if (null != myOverlay.targetOverlay) {
                if (myOverlay.targetOverlay.isRemoved()) {
                    myOverlay.targetOverlay.remove();
                }
                myOverlay.targetOverlay = null;
            }
        }
        myOverlays.clear();
        myOverlays = null;
        if (null != mapView) {
            mapView.onDestroy();
        }
        mIconView = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mapView) {
            mapView.onResume();
        }
        Log.e("三大", "onResume");
        setUnperfornedTask();
    }

    public void setUnperfornedTask() {
        UnperformedTask unperformedTask = UnperformedTask.getInstance();
        if (!unperformedTask.isDoTask()) {
            if (null != unDoTask) {
                if (unperformedTask.getTaskType() == 1) {
                    unDoTask.setText("直航任务");
                } else {
                    unDoTask.setText("导航任务");
                }
            }
        } else {
            if (null != unDoTask) {
                unDoTask.setText("结束任务");
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != mapView) {
            mapView.onPause();
        }
    }

    /**
     * 下位机位置信息处理
     *
     * @param message
     */
    private void refreshLocation(String message) {
        runOnUiThread(() -> {
            if (null == myOverlays) return;
            String[] info = message.split("-");
            String imei = info[2];
            String locationInfo = info[1];
            String[] location = locationInfo.split(",");
            LatLng point = CoordinateTransformUtil.gpsToBaidu(
                    new LatLng(Double.valueOf(location[0]), Double.valueOf(location[1])));
            if (!isHasMyOverlayWithImei(imei)) {
                myOverlays.add(createNewsMyOverlay(imei, point));
            } else {
                MyOverlay oldOverlay = getMyOverlayWithImei(imei);
                if (null != oldOverlay) {
                    if (TextUtils.isEmpty(oldOverlay.imei)) {
                        oldOverlay.imei = imei;
                    }
                    if (null != oldOverlay.targetOverlay) {
                        if (!oldOverlay.targetOverlay.isRemoved()) {
                            Bundle bundle = oldOverlay.targetOverlay.getExtraInfo();
                            if (bundle.getDouble("latitude") == Double.valueOf(location[0]) &&
                                    bundle.getDouble("longitude") == Double.valueOf(location[1])) {
                            } else {
                                ((Marker) oldOverlay.targetOverlay).setPosition(point);
                            }
                        } else {
                            oldOverlay.bitmapDescriptor = getBitmapDescriptorFromMyOverlay(oldOverlay, oldOverlay.imei, oldOverlay.isSelect);
                            oldOverlay.targetOverlay = baiduMap.addOverlay(oldOverlay.markerOptions.position(point)
                                    .icon(oldOverlay.bitmapDescriptor));
                        }
                    } else {
                        oldOverlay.bitmapDescriptor = getBitmapDescriptorFromMyOverlay(oldOverlay, imei, oldOverlay.isSelect);
                        oldOverlay.targetOverlay = baiduMap.addOverlay(oldOverlay.markerOptions.position(point).icon(oldOverlay.bitmapDescriptor));
                    }
                } else {
                    myOverlays.add(createNewsMyOverlay(imei, point));
                }
            }
            if (null == circles) {
                circles = new ArrayList<>();
            }
            if (circles.size() > 0) {
                Overlay cir = circles.get(circles.size() - 1);
                if (cir instanceof Circle) {
                    Circle circle = ((Circle) cir);
                    LatLng latLng = circle.getCenter();
                    if (latLng.latitude != point.latitude || latLng.longitude != point.longitude) {
                        circles.add(baiduMap.addOverlay(circleOptions.center(point).fillColor(colors[getMyOverlayPositionWithImei(imei)])));
                    }
                }
            } else {
                circles.add(baiduMap.addOverlay(circleOptions.center(point)));
            }
        });
    }

    /**
     * 百度地图marker点击事件处理
     *
     * @param marker
     * @return
     */
    private boolean setMarker(Marker marker) {
        Bundle info = marker.getExtraInfo();
        if (null == info) {
            return clickReturnPointMarjer(marker);
        } else {
            if (!TextUtils.isEmpty(info.getString("IMEI"))) {
                return clickHangXingQiMarker(marker);
            } else return false;
        }
    }

    /**
     * 返航标志点击事件回调
     *
     * @param marker
     * @return
     */
    private boolean clickReturnPointMarjer(Marker marker) {
        ShowReturnPointDialogFragment dialog = ShowReturnPointDialogFragment.getInstance(marker.getPosition());
        dialog.setOnShowReturnPointDialogListener(latLng -> setReturnPoint(latLng));
        dialog.show(getSupportFragmentManager(), "ShowReturnPointDialogFragment");
        return true;
    }

    /**
     * auv图标点击事件回调
     *
     * @param marker
     * @return
     */
    private boolean clickHangXingQiMarker(Marker marker) {
        if (isHasMyOverlayWithMarker(marker)) {
            MyOverlay myOverlay = getMyOverlayWithMarker(marker);
            if (null != myOverlay) {
                myOverlay.isSelect = !myOverlay.isSelect;
                if (null != myOverlay.bitmapDescriptor) {
                    myOverlay.bitmapDescriptor.recycle();
                }
                myOverlay.bitmapDescriptor = changeView2Drawble(myOverlay.imei, myOverlay.isSelect);
                if (null != myOverlay.targetOverlay) {
                    if (!myOverlay.targetOverlay.isRemoved()) {
                        ((Marker) myOverlay.targetOverlay).setIcon(myOverlay.bitmapDescriptor);
                    } else {
                        myOverlay.targetOverlay = baiduMap.addOverlay(myOverlay.markerOptions.icon(myOverlay.bitmapDescriptor));
                    }
                } else {
                    myOverlay.targetOverlay = baiduMap.addOverlay(myOverlay.markerOptions.icon(myOverlay.bitmapDescriptor));
                }
                String imei = marker.getExtraInfo().getString("IMEI");
                HeartbeatInfo info = getHeartbeatInfoByImei(imei);
                if (myOverlay.isSelect) {
                    UdpSocket.getInstance().sendMessage("B" + imei
                            + "getAuvAndPhoneElectricQuantity");
                } else {
                    if (null != info) {
                        info.isShwoElectricQuantity = false;
                        heartbeatAdapter.notifyItemChanged(heartbeatInfos.indexOf(info), 1);
                    }
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * @param imei
     * @param point
     * @return
     */
    private MyOverlay createNewsMyOverlay(String imei, LatLng point) {
        BitmapDescriptor bit = changeView2Drawble(imei, false);
        MyOverlay myOverlay = new MyOverlay();
        myOverlay.imei = imei;
        myOverlay.isSelect = false;
        myOverlay.markerOptions = createTargetMarkerOptions(point, imei, bit);
        myOverlay.targetOverlay = baiduMap.addOverlay(myOverlay.markerOptions);
        myOverlay.bitmapDescriptor = bit;
        return myOverlay;
    }

    private MarkerOptions createTargetMarkerOptions(LatLng point, String imei, BitmapDescriptor bit) {
        Bundle bundle = new Bundle();
        bundle.putString("IMEI", imei);
        bundle.putDouble("latitude", point.latitude);
        bundle.putDouble("longitude", point.longitude);
        MarkerOptions markerOptions = new MarkerOptions()
                .position(point)
                .icon(bit)
                .zIndex(auvPriority)
                .animateType(MarkerOptions.MarkerAnimateType.none)
                .extraInfo(bundle);
        return markerOptions;
    }

    public List<MyOverlay> getSelectedOverlay() {
        if (null == myOverlays || myOverlays.size() == 0) return null;
        List<MyOverlay> overlays = new ArrayList<>();
        for (MyOverlay overlay : myOverlays) {
            if (!TextUtils.isEmpty(overlay.imei) && overlay.isSelect) {
                overlays.add(overlay);
            }
        }
        return overlays;
    }

    public void clearMyOverlays() {
        if (null == myOverlays || myOverlays.size() == 0) return;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.targetOverlay || !myOverlay.targetOverlay.isRemoved()) {
                myOverlay.targetOverlay.remove();
            }
        }
        if (null == circles || circles.size() == 0) return;
        for (Overlay overlay : circles) {
            if (!overlay.isRemoved()) {
                overlay.remove();
            }
        }
        circles.clear();
    }

    private BitmapDescriptor getBitmapDescriptorFromMyOverlay(MyOverlay myOverlay, String text, boolean isShow) {
        if (null == myOverlay) return null;
        if (null == myOverlay.bitmapDescriptor || null == myOverlay.bitmapDescriptor.getBitmap() || myOverlay.bitmapDescriptor.getBitmap().isRecycled()) {
            return changeView2Drawble(text, isShow);
        } else {
            return myOverlay.bitmapDescriptor;
        }
    }

    private boolean isHasMyOverlayWithMarker(Marker marker) {
        if (null == myOverlays || myOverlays.size() == 0 || null == marker) return false;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.targetOverlay && myOverlay.targetOverlay == marker) {
                return true;
            }
        }
        return false;
    }

    private MyOverlay getMyOverlayWithMarker(Marker marker) {
        if (null == myOverlays || myOverlays.size() == 0 || null == marker) return null;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.targetOverlay && myOverlay.targetOverlay == marker) {
                return myOverlay;
            }
        }
        return null;
    }

    private boolean isHasMyOverlayWithImei(String imei) {
        if (null == myOverlays || myOverlays.size() == 0 || TextUtils.isEmpty(imei)) return false;
        boolean isHas = false;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.imei && myOverlay.imei.equals(imei)) {
                isHas = true;
            }
        }
        return isHas;
    }

    private MyOverlay getMyOverlayWithImei(String imei) {
        if (null == myOverlays || myOverlays.size() == 0 || TextUtils.isEmpty(imei)) return null;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.imei && myOverlay.imei.equals(imei)) {
                return myOverlay;
            }
        }
        return null;
    }

    private int getMyOverlayPositionWithImei(String imei) {
        if (null == myOverlays || myOverlays.size() == 0 || TextUtils.isEmpty(imei)) return -1;
        for (MyOverlay myOverlay : myOverlays) {
            if (null != myOverlay.imei && myOverlay.imei.equals(imei)) {
                return myOverlays.indexOf(myOverlay);
            }
        }
        return -1;
    }

    private BitmapDescriptor changeView2Drawble(String text, boolean isShow) {
        if (null == mIconView) {
            mIconView = LayoutInflater.from(this).inflate(R.layout.custom_bd_pop, null);
        }
        View icon = mIconView.findViewById(R.id.icon);
        TextView tv = mIconView.findViewById(R.id.tv);
        tv.setText(text);//文字过长可以做处理
        if (isShow) {
            tv.setVisibility(View.VISIBLE);
        }
        tv.setVisibility(isShow ? View.VISIBLE : View.GONE);
//        icon.setRotation(-angle);
        mIconView.setDrawingCacheEnabled(true);
        mIconView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mIconView.layout(0, 0,
                mIconView.getMeasuredWidth(),
                mIconView.getMeasuredHeight());
        mIconView.buildDrawingCache();
        //获取到图片，这样就可以添加到Map上
        return BitmapDescriptorFactory.fromView(mIconView);
    }

    private void showSettingDaoHangDialog() {
        HeaderDialog headerDialog = new HeaderDialog(this);
        headerDialog.setColor(getResources().getColor(R.color.Control3)) // Sets the header background color
                .setElevation(false) // Sets the header elevation, true by default
                .setIcon(getResources().getDrawable(R.drawable.ic_content_paste_black_24dp)) // Sets the dialog icon image
                .setTitle(getResources().getString(R.string.addparameter)) // Sets the dialog title
                .setMessage("") // Sets the dialog message
                .justifyContent(true) // Justifies the message text, false by default
                .setTitleColor(Color.parseColor("#212121")) // Sets the header title text color
                .setIconColor(Color.parseColor("#212121")) // Sets the header icon color
                .setTitleGravity(Gravity.CENTER_HORIZONTAL) // Sets the header title text gravity
                .setMessageGravity(Gravity.CENTER_HORIZONTAL) // Sets the message text gravity
                .setTitleMultiline(false) // Multiline header title text option, true by default
                .setView(R.layout.sailtask_test_dialog) // Set custom view to the dialog (only possible via layout resource)
                .setPositiveButton("确定", ((dialog, which) -> {
                    EditText editParameter = headerDialog.getInflatedView().findViewById(R.id.input1);
                    String content1 = editParameter.getText().toString();
                    if (!content1.contentEquals("")) {
                        sendOrderByCondition("gps," + content1);
                    }
                }))
                .setNegativeButton("取消", ((dialog, which) -> {
                })).create();
        headerDialog.show();
    }

    private void showSettingZhiHangDialog() {
        HeaderDialog headerDialog = new HeaderDialog(this);
        headerDialog.setColor(getResources().getColor(R.color.Control3)) // Sets the header background color
                .setElevation(false) // Sets the header elevation, true by default
                .setIcon(getResources().getDrawable(R.drawable.ic_content_paste_black_24dp)) // Sets the dialog icon image
                .setTitle(getResources().getString(R.string.addparameter)) // Sets the dialog title
                .setMessage("请在下面添加AUV的直航参数") // Sets the dialog message
                .justifyContent(true) // Justifies the message text, false by default
                .setTitleColor(Color.parseColor("#212121")) // Sets the header title text color
                .setIconColor(Color.parseColor("#212121")) // Sets the header icon color
                .setTitleGravity(Gravity.CENTER_HORIZONTAL) // Sets the header title text gravity
                .setMessageGravity(Gravity.CENTER_HORIZONTAL) // Sets the message text gravity
                .setTitleMultiline(false) // Multiline header title text option, true by default
                .setView(R.layout.sailtask_straight_dialog) // Set custom view to the dialog (only possible via layout resource)
                .setPositiveButton("确定", ((dialog, which) -> {
                    EditText editTime = headerDialog.getInflatedView().findViewById(R.id.input1);
                    EditText editSpeed = headerDialog.getInflatedView().findViewById(R.id.input2);
                    EditText editDepth = headerDialog.getInflatedView().findViewById(R.id.input3);
                    EditText editParameter = headerDialog.getInflatedView().findViewById(R.id.input4);
                    String content1 = editTime.getText().toString();
                    String content2 = editSpeed.getText().toString();
                    String content3 = editDepth.getText().toString();
                    String content4 = editParameter.getText().toString();
                    if (content4.contentEquals("")) {
                        content4 = "0.5,0.1,1.0,0.5,1";
                    }
                    if (!content1.contentEquals("") && !content2.contentEquals("")
                            && !content3.contentEquals("")) {
                        String orderComment = "afa," + content1 + "," + content2 + "," + content3 + "," + content4;
                        if (orderComment.split(",").length != 9) {
                            Toast.makeText(ControlActivity.this, "请输入正确的参数", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        List<MyOverlay> selects = getSelectedOverlay();
                        if (null == selects || selects.size() == 0) {
                            Toast.makeText(this, "请先选中指定auv", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        List<String> strs = new ArrayList<>();
                        for (MyOverlay myOverlay : selects) {
                            strs.add(myOverlay.imei);
                        }
                        UnperformedTask.getInstance().setDirectRoute(Integer.valueOf(content1),
                                Integer.valueOf(content2), Integer.valueOf(content3), content4, strs);
                        Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
                        setUnperfornedTask();
                    }
                }))
                .setNegativeButton("取消", (dialog, which) -> {
                }).create();
        headerDialog.show();
    }
}
